/*
 * @LastEditTime: 2023-02-28 11:30:54
 */
import { Collection } from "../Models/Collection.schema";
import { createCollectionDTO, updateCollectionDTO } from "../DTO/Collection.dto";
import { isExistsforId, isExistsforUsername } from "../hook";

export class CollectionController {
  constructor(private readonly collectionModel: typeof Collection) { }

  /**
   * 创建收藏
   * @param dto 数据传输对象
   * @returns 返回创建对象
   */
  async createItem(dto: createCollectionDTO) {
    try {
      const res = await this.collectionModel.find({ username: dto.username })
      for (let i = 0; i < res.length; i++) {
        if (res[i].musicListid === dto.musicListid.toString()) {
          console.log(123)
          return {
            code: 200,
            message: "该歌单已经收藏",
          }
        }
      }
      return {
        code: 200,
        message: "收藏成功",
        data: await this.collectionModel.create(dto),
      };

    } catch (error) {
      return await error;
    }
  }

  /**
   * 按ID更新收藏
   * @param id 要更新的ID
   * @param dto  要更新的内容
   * @returns 更新对象
   */
  async updateById(id: string, dto: updateCollectionDTO) {
    try {
      if (!!await isExistsforId(id, this.collectionModel)) {
        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "更新成功",
          data: await this.collectionModel.updateOne({ _id: id }, dto),
        };
        console.log(1)
      }
    } catch (error) {
      return await error;
    }
  }

  /**
   * 按收藏名称查找收藏
   * @param title 要查找的收藏名称
   * @returns 查询对象
   */
  async findByUsername(name: string) {
    try {
      if (await isExistsforUsername(name, this.collectionModel)) {
        return {
          code: 200,
          message: '暂无数据',
        }
      } else {
        return {
          code: 200,
          message: "查询成功",
          data: await this.collectionModel.find({ username: name }),
        };
      }
    } catch (error) {
      return await error;
    }
  }


  /**
   * 按ID查找收藏
   * @param id 要查找的收藏名称
   * @returns 查询对象
   */
  async findById(id: string) {
    try {
      if (!await isExistsforId(id, this.collectionModel)) {

        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "查询成功",
          data: await this.collectionModel.find({ _id: id }),
        };
      }
    } catch (error) {
      return false;
    }
  }
  //查询全部数据
  async findAll() {
    try {
      if (await this.collectionModel.find().count() != 0)
        return {
          code: 200,
          message: "查询成功",
          data: await this.collectionModel.find(),
        };
      else
        return {
          code: 400,
          message: "该数据集不存在数据"
        }
    }
    catch (error) {
      return await error;
    }
  }
}